<template>
  <div class="login">
    <login-header>
      <el-form 
        :model="ruleForm"
        :rules="rules"
        slot="container"
        label-position="left"
        label-width="0px"
        ref="ruleForm"
        >
        <div class="title">
          <h3>账号密码登录</h3>
        </div>
        <el-form-item prop="username">
          <el-input 
            type="text" 
            v-model="ruleForm.username" 
            prefix-icon="el-icon-user" 
            auto-complete="off"
            placeholder="账号"
            />
        </el-form-item>
        <el-form-item
          prop="pwd">
          <el-input 
            type="password" 
            v-model="ruleForm.pwd" 
            prefix-icon="el-icon-lock" 
            placeholder="密码"
            />
        </el-form-item>
        <el-form-item>
          <el-button
            :loading="isShowLoading"
            type="primary" 
            style="width:100%"
            @click.native.prevent="handleSubmit"
            >登录</el-button>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="ruleForm.autoLogin" :checked="ruleForm.autoLogin">7天内自动登录</el-checkbox>
          <el-button 
            @click="$router.push('/password')" 
            type="text" 
            class="forget"
            >忘记密码?</el-button>
        </el-form-item>
      </el-form>
    </login-header>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Provide } from "vue-property-decorator";
import LoginHeader from "./LoginHeader.vue";
import {State,Getter,Mutation,Action}from "vuex-class"

@Component({
  components: {
    LoginHeader
  }
})
export default class LayoutHeader extends Vue {
  @Action("setUser") setUser: any;
  @Provide() isShowLoading: boolean = false;
  @Provide() ruleForm: {
    username: string,
    pwd: string,
    autoLogin: boolean
  } = {
    username: "",
    pwd: "",
    autoLogin: true
  }

  @Provide() rules = {
    username:[{ required: true, message: '请输入账号', trigger: 'blur' },],
    pwd:[{ required: true, message: '请输入密码', trigger: 'blur' },]
  }


  handleSubmit(): void {
    (this.$refs["ruleForm"] as any).validate((vali: boolean) => {
      if(vali) {
        this.isShowLoading = true;
        (this as any).$axios
          .post("/api/users/login", this.ruleForm)
          .then((res: any) => {
            this.isShowLoading = false
            localStorage.setItem("token", res.data.token)
            this.setUser(res.data.token)
            this.$router.push("/")
          })
          .catch(() => {
            this.isShowLoading = false
          })
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
}
.forget {
  float: right;
}
</style>
